package com.company.statis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.servicebase.exception.MyException;
import com.company.statis.entity.StatisticsDaily;
import com.company.statis.feign.UserFeignService;
import com.company.statis.mapper.StatisticsDailyMapper;
import com.company.statis.service.StatisticsDailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.utils.DateUtil;
import com.company.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-04-24
 */
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {

    @Resource
    private UserFeignService userFeignService;

    @Override
    @Transactional
    public void saveStatistics(String date) {

        if(!date.equals(DateUtil.formatDate(new Date()))) {
            throw new MyException(20001, "只能生成当前日的数据！");
        }

        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.eq("date_calculated", date);
        StatisticsDaily daily = this.getOne(wrapper);

        Integer registerCount = userFeignService.getRegisterCount(date);
        StatisticsDaily statisticsDaily = new StatisticsDaily();
        statisticsDaily.setDateCalculated(date);
        statisticsDaily.setRegisterNum(registerCount);
        statisticsDaily.setVideoViewNum(80);
        if (daily == null) {
            this.save(statisticsDaily);
        } else {
            this.removeById(daily.getId());
            this.save(statisticsDaily);
        }

    }

    @Override
    public Map<String, Object> show(String type, String begin, String end) {
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.between("date_calculated", begin, end).select("date_calculated", type);
        List<StatisticsDaily> list = this.list(wrapper);

        List<String> date_calculatedList = new ArrayList<>();
        List<Integer> numDataList = new ArrayList<>();
        list.forEach((entity) -> {
            date_calculatedList.add(entity.getDateCalculated());
            switch (type) {
                case "register_num":
                    numDataList.add(entity.getRegisterNum());
                    return;
                case "video_view_num":
                    numDataList.add(entity.getVideoViewNum());
                    return;
            }
        });

        Map<String, Object> map = new HashMap<>(10);
        map.put("date_calculatedList", date_calculatedList);
        map.put("numDataList", numDataList);
        return map;
    }

}
